package com.source.multithread.thread;


import javafx.scene.control.cell.CheckBoxTreeTableCell;
import jdk.nashorn.internal.ir.CatchNode;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author wengqy
 * @Date 2020/12/16
 */
public class ThreadExcutorsDemo {
    public static void main(String[] args) throws InterruptedException {
             MyRunnable myRunnable = new MyRunnable();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                5,
                5,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );

        try {

            for (int i = 1; i <= 13; i++) {
            //    TimeUnit.MILLISECONDS.sleep(100);

            //    threadPoolExecutor.execute( new MyRunnable());
                threadPoolExecutor.execute( myRunnable);

            }
        } catch (Exception ee) {

        } finally {
            threadPoolExecutor.shutdown();
        }
       /* MyRunnable  myRunnable  = new MyRunnable();

       new Thread(myRunnable,"AA").start();
       Thread.sleep(100);
       new Thread(myRunnable,"BB").start();
       new Thread(myRunnable,"CC").start();
       new Thread(myRunnable,"DD").start();
       new Thread(myRunnable,"EE").start();
       new Thread(myRunnable,"FF").start();*/


    }


}

class MyRunnable implements Runnable {
    private      int ticket = 20;
    boolean flag = true;

    @SneakyThrows
    @Override
    public void run() {
        /*while (flag) {
            if (count > 0) {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                   decrement();
                 //   count--;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                flag=false;
                break;
            }
        }*/
        while(flag){
            decrement();
        }

    }

    private  synchronized void decrement() {
        if(ticket<=0){
            flag =false;
            return;
        }
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "-------::::" +   ticket--);
    }
}
